#-*- codeing = utf-8 -*-
#@Time : 2020/10/20 22:42
#@Author : 阳某
#@File : Pandas按行遍历DataFrame的3种方法.py
#@Software : PyCharm

import pandas as pd
import numpy as np
import collections
df = pd.DataFrame(
    np.random.random(size=(100000, 4)),
    columns=list('ABCD')
)
print(df.head(3))
print(df.shape)
# 1. df.iterrows()
# 使用方式
print(df.iterrows())
for idx, row in df.iterrows():
    print(idx, row)
    print('**********')
    print(idx, row["A"], row["B"], row["C"], row["D"])
    break
'''
时间耗费
%%time
result = collections.defaultdict(int)
for idx, row in df.iterrows():
    result[(row["A"], row["B"])] += row["A"] + row["B"]
    
CPU times: user 7.82 s, sys: 35.6 ms, total: 7.85 s
Wall time: 7.89 s    
'''
# 2. df.itertuples()
# 使用方式
for row in df.itertuples():
    print(row)
    print(row.Index, row.A, row.B, row.C, row.D)
    break

'''
时间耗费
%%time
result = collections.defaultdict(int)
for row in df.itertuples():
    result[(row.A, row.B)] += row.A + row.B
    
CPU times: user 168 ms, sys: 8.35 ms, total: 177 ms
Wall time: 178 ms 
'''

# 3. for+zip
# 使用方式
#  既不需要类型检查，也不需要构建namedtuple
# 缺点是需要挨个指定变量
for A, B in zip(df["A"], df["B"]):
    print(A, B)
    break

'''
%%time
result = collections.defaultdict(int)
for A, B in zip(df["A"], df["B"]):
    result[(A, B)] += A + B
    
CPU times: user 82.2 ms, sys: 7.05 ms, total: 89.2 ms
Wall time: 89.9 ms
'''